package mysql;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class TestJDBC_v {

	private static Properties props = initProps();

	static {
		initProps();
	}

	public static void main(String[] args) {
		Connection conn = null;
		try {

			String driverEspecific = getPropietat("rdbms.driver");
			Class.forName(driverEspecific).newInstance();
			conn = DriverManager.getConnection("rdbms.url", "rdbms.usuario",
					"rdbms.pwd");

			mostrarInfoMetadata(conn);
			mostrarPelicules(conn);

		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException | SQLException e) {

			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private static void mostrarPelicules(Connection conn) {

		try {
			
			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery("select * from pel");
			while (rs.next()){
				System.out.println(
						rs.getInt("p_num")+"-"+rs.getString("titulo"));
			}
			
		} catch (SQLException e) {

			e.printStackTrace();
		}

	}

	private static void mostrarInfoMetadata(Connection conn) {
		try {
			DatabaseMetaData dbmd = conn.getMetaData();
			System.out.println("nom driver: " + dbmd.getDriverName());
			System.out.println("version driver: " + dbmd.getDriverVersion());
			System.out.println("nom rdmbs: " + dbmd.getDatabaseProductName());
			System.out.println("versio rdmbs: "
					+ dbmd.getDatabaseProductVersion());
			System.out.println("catalegs en el rdbms: ");
			ResultSet rs = dbmd.getCatalogs();
			while (rs.next()) {
				System.out.println("-" + rs.getString(1));
			}

		} catch (SQLException e) {

			e.printStackTrace();
		}

	}

	private static Properties initProps() {
		InputStream is = TestJDBC_v.class.getResourceAsStream("/db.properties");
		Properties props = new Properties();
		try {
			props.load(is);
			return props;
		} catch (IOException e) {
			e.printStackTrace();
		}
		throw new RuntimeException(
				"Error cargando el fichero de propiedades de la BD");
	}

	private static String getPropietat(String propietat) {

		return props.getProperty(propietat);

	}

}
